package com.learn.framework.aspectj;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.learn.common.enums.LogType;
import com.learn.common.utils.JwtUtil;
import com.learn.core.domain.LLog;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.service.ILLogService;
import com.learn.core.service.ILUserService;
import com.learn.core.service.IUserDetailsGatherService;
import io.undertow.security.api.SecurityContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import com.learn.common.annotation.Log;
import com.learn.common.cons.APICons;
//import com.learn.common.utils.security.ShiroUtils;
//import com.learn.framework.manager.factory.TimerTasks;
import com.learn.framework.spring.ApplicationUtils;
//import com.learn.framework.utils.LogUtils;
//import com.learn.project.monitor.operlog.domain.OperLog;
//import com.learn.project.system.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 操作日志记录处理
 *
 * @author Crown
 */
@Aspect
@Component
@Slf4j
class LogAspect {

    @Autowired
    ILLogService ilLogService;
    @Autowired
    private IUserDetailsGatherService iUserDetailsGatherService;

    // 配置织入点
    @Pointcut("execution(public * com.learn.*.*.manager.*Controller.*(..))")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     * @param ret       返回值
     */
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint, Object ret) {
        handleLog(joinPoint, ret, null);
    }

//    /**
//     * 拦截异常操作
//     *
//     * @param joinPoint 切点
//     * @param e         异常
//     */
//    @AfterThrowing(value = "logPointCut()", throwing = "e")
//    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
//        handleLog(joinPoint, null, e);
//    }

    protected void handleLog(final JoinPoint joinPoint, final Object ret, final Exception e) {
        try {
            HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            // 获取用户信息
            String token = request.getHeader("token");
            String userId = JwtUtil.getUserId(token);

            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            String actionMethod = className + "." + methodName + "()";
            ApplicationUtils.getRequest().setAttribute(APICons.API_ACTION_METHOD, actionMethod);
            String requestURI = (String) ApplicationUtils.getRequest().getAttribute(APICons.API_REQURL);

            // 获得注解
            Method method = getMethod(joinPoint);
            Log controllerLog = getAnnotationLog(method);
            if (controllerLog == null) {
                return;
            }
            // *========数据库日志=========*//
            LLog lLog = new LLog();
            lLog.setLogUrl(requestURI);
            lLog.setCreateTime(new Date());
            QueryWrapper<UserDetailsGather> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(queryWrapper);
            if(null != userDetailsGather){
                lLog.setCreateUser(userDetailsGather.getName());
            }
            // 日志类型
            lLog.setLogType(controllerLog.logType().getInfo());
            // 业务模块
            lLog.setBusinessModule(controllerLog.operatorType().getInfo());
            // 详情
            lLog.setDescription(controllerLog.title());
            // 操作类型
            lLog.setOperationType(controllerLog.businessType().getInfo());
            ilLogService.save(lLog);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

//    /**
//     * 获取注解中对方法的描述信息 用于Controller层注解
//     *
//     * @param log     日志
//     * @param operLog 操作日志
//     */
//    public void getControllerMethodDescription(Log log, OperLog operLog) {
//        // 设置action动作
//        operLog.setBusinessType(log.businessType().ordinal());
//        // 设置标题
//        operLog.setTitle(log.title());
//        // 设置操作人类别
//        operLog.setOperatorType(log.operatorType().ordinal());
//        // 是否需要保存request，参数和值
//        if (log.isSaveRequestData()) {
//            // 获取参数的信息，传入到数据库中。
//            setRequestValue(operLog);
//        }
//    }

//    /**
//     * 获取请求的参数，放到log中
//     *
//     * @param operLog
//     */
//    private void setRequestValue(OperLog operLog) {
//        Map<String, String[]> map = ApplicationUtils.getRequest().getParameterMap();
//        String params = JsonUtils.toJson(map);
//        operLog.setOperParam(StringUtils.substring(params, 0, 2000));
//    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(Method method) {
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }

    /**
     * 获取Method
     *
     * @param joinPoint
     * @return
     */
    private Method getMethod(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        return methodSignature.getMethod();
    }
}
